<template>
  <div class="dm">
    <div class="dm-full" :style="{width: pageWidth+'px'}">
      <div class="dm-data" v-loading="loading">
        <div class="dm-data-top">
          <div class="dm-data-actions">
            <ListCascaderDialog :multiple="true"
                                :panel1="userSelectPanel1"
                                :panel2="userSelectPanel2"
                                @onConfirm="doUsersCascaderConfirm">
              <a-button>重新选人</a-button>
            </ListCascaderDialog>
          </div>
        </div>
        <Table :data="dataRows" size="small" stripe :height="pageHeight-68">
          <TableColumn prop="name" label="姓名" width="150" />
          <TableColumn width="200">
            <span slot="header">
              <span style="margin-right: 5px;">主工作单位</span>
              <TreeSelectDialog dataUrl="/jsofted/org/tree" @onConfirm="doOrgSelectConfirm">
                <a-button title="批量调整主工作单位" size="small" type="link" icon="form" />
              </TreeSelectDialog>
            </span>
            <span slot-scope="{row}">
                <TreeSelectDialog dataUrl="/jsofted/org/tree" :value="row.orgId"
                                    @onConfirm="doOrgSelectConfirm($event, row)">
                  {{row.orgFullName}}
                  <a-button size="small" type="link" icon="form" />
                </TreeSelectDialog>
            </span>
          </TableColumn>
          <TableColumn width="150">
            <span slot="header">
              <span style="margin-right: 5px;">主要职位</span>
              <TreeSelectDialog dataUrl="/jsofted/post/tree" @onConfirm="doPostSelectConfirm">
                <a-button title="批量调整主要职位" size="small" type="link" icon="form" />
              </TreeSelectDialog>
            </span>
            <span slot-scope="{row}">
                <TreeSelectDialog dataUrl="/jsofted/post/tree"
                                  :query-params="{orgId: row.orgId}"
                                  :value="row.postId"
                                  @onConfirm="doPostSelectConfirm($event, row)">
                  {{row.postName}}
                  <a-button size="small" type="link" icon="form" />
                </TreeSelectDialog>
            </span>
          </TableColumn>
          <TableColumn min-width="300">
            <span slot="header">
              <span style="margin-right: 5px;">一人多岗</span>
              <a-popconfirm title="您确定要清除全部人的一人多岗吗？" placement="top" @confirm="doClearPosts">
                  <a-button title="批量清除全部人的一人多岗" size="small" type="link" icon="delete" />
              </a-popconfirm>
              <TreeCascaderDialog multiple tree-result
                                  :panel1="postCascaderPanel1()"
                                  :panel2="postCascaderPanel2()"
                                  @onConfirm="doPostCascaderConfirm">
                <a-button title="批量新增一人多岗" size="small" type="link" icon="plus" />
              </TreeCascaderDialog>
            </span>
            <span slot-scope="{row}">
                <TreeCascaderDialog multiple tree-result no-border
                                    :panel1="postCascaderPanel1()"
                                    :panel2="postCascaderPanel2()"
                                    :results="postCascaderResults(row)"
                                    @onConfirm="refreshDataRows">
                </TreeCascaderDialog>
            </span>
          </TableColumn>
        </Table>
      </div>
    </div>
  </div>
</template>
<script>
import DataFormJS from '@/utils/DataFormUtils'
import {Table, TableColumn} from 'element-ui'

export default {
  mixins: [DataFormJS],
  components: {Table, TableColumn},
  data() {
    return {
      queryUrl: '/jsofted/user/list/',
      dataRows: [],
      queryDataRows: window.$debounce(this._queryDataRows),
      loading: false,
      userSelectPanel1: {
        dataUrl: '/jsofted/org/tree',
        title: '按单位筛选',
      },
      userSelectPanel2: {
        dataUrl: '/jsofted/user/list',
        casField: 'orgId',
      },
      currIdList: []
    }
  },
  watch: {
  },
  methods: {
    init() {
      // console.log('init: %s', JSON.stringify(this.pageParams))
      this.currIdList = this.pageParams.idList
      this.queryDataRows()
    },
    postCascaderPanel1() {
      return {
        dataUrl: '/jsofted/org/tree',
        title: '第1步：选择单位',
        emptyText: '暂无单位选项'
      }
    },
    postCascaderPanel2() {
      return {
        dataUrl: '/jsofted/post/tree',
        casField: 'orgId',
        title: '第2步：选择职位',
        emptyText: '暂无职位选项'
      }
    },
    /**
     * 人员职位中间表编辑器参数——中间表参数
     */
    postCascaderResults(row) {
      return {
        dataUrl: '/jsofted/userPost/list',
        leftField: 'userId',
        leftValue: row.id,
        rightField1: 'orgId',
        rightNameField1: 'orgFullName',
        rightField2: 'postId',
        rightNameField2: 'postName',
        saveUrl: '/jsofted/userPost/deleteThenAdd',
        emptyText: '暂无选中的职位'
      }
    },
    refreshDataRows() {
      setTimeout(() => {
        this.queryDataRows()
      }, 300)
    },
    _queryDataRows() {
      if (!this.queryUrl) {
        return
      }
      this.loading = true
      this.$http.post(this.queryUrl, {idList: this.currIdList}).then((rs) => {
        this.loading = false
        const result = rs.data
        if (result.success) {
          this.dataRows = result.data
        } else {
          this.dataRows = []
        }
      })
    },
    doClearPosts() {
      let idList = []
      this.dataRows.forEach(row => {
        idList.push(row.id)
      })
      this.loading = true
      this.$http.post('/jsofted/userPost/deleteBy', {userId: idList}).then((rs) => {
        this.loading = false
        const result = rs.data
        if (result.success) {
          this.$message.success(result.message)
          this.queryDataRows()
        } else {
          this.$alert.error({title: result.message})
        }
      })
    },
    doUsersCascaderConfirm({rows, keys}) {
      console.log('doUsersCascaderConfirm: keys = %s', JSON.stringify(keys))
      console.log('doUsersCascaderConfirm: rows = %s', JSON.stringify(rows))
      this.currIdList = keys
      this.refreshDataRows()
    },
    doPostCascaderConfirm(tree) {
      // console.log('doRoleSelectConfirm: tree = %s', JSON.stringify(tree))
      let datas = []
      tree.forEach(org => {
        org.children.forEach(post => {
          this.dataRows.forEach(user => {
            datas.push({
              userId: user.id,
              orgId: org.id,
              postId: post.id,
            })
          })
        })
      })
      let uniqueFields = ['userId', 'orgId', 'postId']
      //
      console.log('doRoleSelectConfirm: datas = %s', JSON.stringify(datas))
      //
      this.loading = true
      this.$http.post('/jsofted/userPost/saveAll', {
        uniqueFields: uniqueFields,
        datas: datas
      }).then((rs) => {
        this.loading = false
        const result = rs.data
        if (result.success) {
          this.$message.success(result.message)
          this.refreshDataRows()
        } else {
          this.$alert.error({title: result.message})
        }
      })
    },
    doOrgSelectConfirm(event, user) {
      // console.log('doOrgSelectConfirm: event = %s', JSON.stringify(event))
      // console.log('doOrgSelectConfirm: userId = %s', user ? user.id : '')
      let datas = []
      if (user && user.id) {
        datas.push({
          id: user.id,
          orgId: event.keys
        })
      } else {
        this.dataRows.forEach(user => {
          datas.push({
            id: user.id,
            orgId: event.keys
          })
        })
      }
      let uniqueFields = ['id']
      this.$http.post('/jsofted/user/saveAll', {
        uniqueFields: uniqueFields,
        datas: datas
      }).then((rs) => {
        this.loading = false
        const result = rs.data
        if (result.success) {
          this.$message.success(result.message)
          this.refreshDataRows()
        } else {
          this.$alert.error({title: result.message})
        }
      })
    },
    doPostSelectConfirm(event, user) {
      console.log('doPostSelectConfirm: event = %s', event)
      console.log('doPostSelectConfirm: userId = %s', user ? user.id : '')
      let datas = []
      if (user && user.id) {
        datas.push({
          id: user.id,
          postId: event.keys
        })
      } else {
        this.dataRows.forEach(user => {
          datas.push({
            id: user.id,
            postId: event.keys
          })
        })
      }
      let uniqueFields = ['id']
      this.$http.post('/jsofted/user/saveAll', {
        uniqueFields: uniqueFields,
        datas: datas
      }).then((rs) => {
        this.loading = false
        const result = rs.data
        if (result.success) {
          this.$message.success(result.message)
          this.refreshDataRows()
        } else {
          this.$alert.error({title: result.message})
        }
      })
    }
  }
}
</script>
